/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radiostation;

//import static com.sun.xml.internal.fastinfoset.alphabet.BuiltInRestrictedAlphabets.table;
import java.awt.Color;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.swing.JOptionPane;
import model.Playlist;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author stamatelopoulos
 */
public class ListPlayListForm extends javax.swing.JFrame {

    /**
     * Creates new form ListPlayListForm
     */
    EntityManager em;
    int selectedRow;
    Playlist playlist;
    
    public ListPlayListForm() {
        em = DBManager.em;
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        initComponents();
        manageButtons();
        DBManager.centerOnScreen(this);
        this.PlaylistTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        TableCellRenderer rendererFromHeader = PlaylistTable.getTableHeader().getDefaultRenderer();
        JLabel Id = (JLabel)rendererFromHeader;
        Id.setHorizontalAlignment(JLabel.CENTER);

        JTableHeader header = PlaylistTable.getTableHeader();
        header.setForeground(Color.red);

        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        PlaylistTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
        PlaylistTable.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
        PlaylistTable.getColumnModel().getColumn(3).setCellRenderer(new DateCellRenderer());

    }
    private void manageButtons() {
        selectedRow = PlaylistTable.getSelectedRow();
        editButton.setEnabled(selectedRow >= 0);
        deleteButton.setEnabled(selectedRow >= 0);
        expxmlButton.setEnabled(selectedRow >= 0);
        
        if (selectedRow >= 0) {
            playlist = PlaylistList.get(PlaylistTable.convertRowIndexToModel(selectedRow));
        }
    }
        
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        PlaylistQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select p from Playlist p order by p.name");
        PlaylistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(PlaylistQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        PlaylistTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        expxmlButton = new javax.swing.JButton();
        impxmlButton = new javax.swing.JButton();
        insButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Πίνακας Λιστών Τραγουδιών");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, PlaylistList, PlaylistTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Κωδικός");
        columnBinding.setColumnClass(Long.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Ονομασία");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Περιγραφή");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${creationdate}"));
        columnBinding.setColumnName("Ημερ. Δημιουργίας");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        PlaylistTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                PlaylistTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(PlaylistTable);
        if (PlaylistTable.getColumnModel().getColumnCount() > 0) {
            PlaylistTable.getColumnModel().getColumn(0).setMaxWidth(100);
            PlaylistTable.getColumnModel().getColumn(1).setMaxWidth(200);
            PlaylistTable.getColumnModel().getColumn(2).setMaxWidth(250);
            PlaylistTable.getColumnModel().getColumn(3).setMaxWidth(120);
        }

        jLabel1.setForeground(new java.awt.Color(0, 51, 255));
        jLabel1.setText("Λίστες Τραγουδιών:");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setForeground(new java.awt.Color(255, 0, 0));
        jLabel2.setText("Διαχείριση Λίστας με XML");

        expxmlButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xml.png"))); // NOI18N
        expxmlButton.setText("Εξαγωγή Λίστας σε XML");
        expxmlButton.setToolTipText("Πατήστε για εξαγωγή της Λίστας σε XML");
        expxmlButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                expxmlButtonActionPerformed(evt);
            }
        });

        impxmlButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xml.png"))); // NOI18N
        impxmlButton.setText("Εισαγωγή Λίστας από XML");
        impxmlButton.setToolTipText("Πατήστε για εισαγωγή Λίστας από XML");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(impxmlButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(expxmlButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addGap(36, 36, 36))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(7, 7, 7)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(expxmlButton)
                .addGap(18, 18, 18)
                .addComponent(impxmlButton)
                .addGap(0, 41, Short.MAX_VALUE))
        );

        insButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        insButton.setText("Δημιουργία");
        insButton.setToolTipText("Πατήστε για Δημιουργία νέας Λίστας Τραγουδιών");
        insButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insButtonActionPerformed(evt);
            }
        });

        editButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit.png"))); // NOI18N
        editButton.setText("Ενημέρωση");
        editButton.setToolTipText("Πατήστε για Ενημέρωση υπάρχουσας Λίστας Τραγουδιών");
        editButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editButtonActionPerformed(evt);
            }
        });

        deleteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteButton.setText("Διαγραφή");
        deleteButton.setToolTipText("Πατήστε για Διαγραφή υπάρχουσας Λίστας Τραγουδιών");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        exitButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exit.png"))); // NOI18N
        exitButton.setText("Έξοδος");
        exitButton.setToolTipText("Πατήστε για Επιστροφή στο Κεντρικό Μενού");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 605, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addComponent(insButton)
                        .addGap(18, 18, 18)
                        .addComponent(editButton)
                        .addGap(18, 18, 18)
                        .addComponent(deleteButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(exitButton)
                        .addGap(44, 44, 44))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(editButton)
                    .addComponent(deleteButton)
                    .addComponent(exitButton)
                    .addComponent(insButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void closeMe(boolean exitAndSave) {
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, exitAndSave);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);
    }
    
    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        // TODO add your handling code here:
        closeMe(true);
    }//GEN-LAST:event_exitButtonActionPerformed

    private void insButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insButtonActionPerformed
        // TODO add your handling code here:
        Playlist pl = new Playlist();
        em.persist(pl);
        EditPlayListForm eplf = new EditPlayListForm(pl, false);
        eplf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        
        eplf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent)arg0).exitAndSave) {
                    manageButtons();
                    em.persist(pl);
                    PlaylistList.add(pl);                   
                    em.getTransaction().commit();

                    int row = PlaylistList.size() - 1;
                    PlaylistTable.setRowSelectionInterval(row, row);
                    PlaylistTable.scrollRectToVisible(PlaylistTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else {
                   thisFrame.setEnabled(true);
                   em.getTransaction().rollback();
                   em.getTransaction().begin();
                   java.util.Collection data = PlaylistQuery.getResultList();
                   for (Object entity : data) {
                       em.refresh(entity);  
                   }
                   PlaylistList.clear();
                   PlaylistList.addAll(data);
                   manageButtons();
            }
        }

            public void windowActivated(WindowEvent arg0) {

                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened2");

            }
        });
    }//GEN-LAST:event_insButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        // TODO add your handling code here:
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        selectedRow = PlaylistTable.getSelectedRow();
        playlist = PlaylistList.get(PlaylistTable.convertRowIndexToModel(selectedRow));
        
        if (selectedRow>=0){
            int c = JOptionPane.showConfirmDialog(null, "Επιθυμείτε σίγουρα να διαγράψετε τη Λίστα Τραγουδιών " + playlist.getName() + "?", "Διαγραφή Λίστας Τραγουδιών",JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (c == 0){ 
               Playlist pl = PlaylistList.get(PlaylistTable.convertRowIndexToModel(selectedRow));
               PlaylistList.remove(pl);
               em.remove(pl);
               em.getTransaction().commit(); 
               JOptionPane.showMessageDialog(null, "Η Διαγραφή της Λίστας Τραγουδιών έγινε με επιτυχία!", "ΕΠΙΤΥΧΗΣ ΔΙΑΓΡΑΦΗ", JOptionPane.INFORMATION_MESSAGE);
            }
            manageButtons();
        }
        else{
            JOptionPane.showMessageDialog(null, "Δεν έχετε επιλέξει Λίστα Τραγουδιών για Διαγραφή.", "ΑΝΕΠΙΤΥΧΗΣ ΔΙΑΓΡΑΦΗ", JOptionPane.INFORMATION_MESSAGE);        
        }
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
        // TODO add your handling code here:
        selectedRow = PlaylistTable.getSelectedRow();
        pl = PlaylistList.get(PlaylistTable.convertRowIndexToModel(selectedRow));
        
        EditPlayListForm eplf = new EditPlayListForm(pl, true);
        eplf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);

        eplf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent)arg0).exitAndSave) {
                    em.persist(pl);
                    PlaylistList.set(selectedRow,pl);
                    em.getTransaction().commit(); 
                    thisFrame.setEnabled(true);
                }
                else {
                   thisFrame.setEnabled(true);
                   em.getTransaction().rollback();
                   em.getTransaction().begin();
                   java.util.Collection data = PlaylistQuery.getResultList();
                   for (Object entity : data) {
                       em.refresh(entity);  
                   }
                   PlaylistList.clear();
                   PlaylistList.addAll(data);
                   manageButtons();
            }
        }  
            public void windowActivated(WindowEvent arg0) {

                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened2");

            }
        });
    }//GEN-LAST:event_editButtonActionPerformed

    private void PlaylistTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_PlaylistTableMouseClicked
        // TODO add your handling code here:
        manageButtons();
    }//GEN-LAST:event_PlaylistTableMouseClicked

    private void expxmlButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_expxmlButtonActionPerformed
        // TODO add your handling code here:
        em.refresh(playlist);
        ExportListToXml eltx = new ExportListToXml(playlist);
        eltx.setVisible(true);
        thisFrame =this;
    }//GEN-LAST:event_expxmlButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<model.Playlist> PlaylistList;
    private javax.persistence.Query PlaylistQuery;
    private javax.swing.JTable PlaylistTable;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JButton expxmlButton;
    private javax.swing.JButton impxmlButton;
    private javax.swing.JButton insButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    JFrame thisFrame;
    Playlist pl;
}
